<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
      <el-table-column prop="name" label="名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="price" label="价格" width="180" sortable>
      </el-table-column>
      <el-table-column prop="description" label="描述" width="180" sortable>
      </el-table-column>
      <el-table-column prop="resource" label="资源" min-width="180" sortable>
      </el-table-column>
      <el-table-column prop="type.name" label="类型" min-width="180" sortable>
      </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="query.pageSize" :total="pageInfo.total" style="float:right;">
			</el-pagination>
		</el-col>

    <!--新增或编辑界面
    :visible.sync="outerVisible" 新版本打开对话框
    v-model="productFormVisible" 老版本打开对话框
    -->
		<el-dialog title="新增或编辑" :visible.sync="productFormVisible" :close-on-click-modal="false">
      <el-form :model="product" label-width="80px" :rules="productFormRules" ref="productForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="product.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="product.price" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" >
          <el-input v-model="product.description" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="资源">
          <el-input type="textarea" v-model="product.resource"></el-input>
        </el-form-item>
        <el-form-item label="类型" >
          <el-select v-model="product.type" clearable value-key="id" placeholder="请选择">
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
               必须要写  value-key="id"
            -->
            <el-option
                v-for="item in productTypes"
                :key="item.id"
                :label="item.name"
                :value="item">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="productFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="save" :loading="productLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>

	export default {
		data() {
			return {
        //分页相关
        query:{
          currentPage:1,
          pageSize:10,
          keyword:''
        },
        pageInfo:{
          total:0,
          rows:[]
        },
				listLoading: false,
				sels: [],//列表选中列

				productFormVisible: false,//新增界面是否显示
				productLoading: false,
				productFormRules: {
					key: [
						{ required: true, message: '请输入键', trigger: 'blur' }
					],
					value: [
						{ required: true, message: '请输入值', trigger: 'blur' }
					]
				},
				//新增界面数据
				product: {
          id:null,
          name: '',
          price:'',
          description:'',
          resource:'',
          type: {}
        },
        productTypes:[]
			}

		},
		methods: {
      getProductType(){
        //发起请求获取数据
        this.$http.get("/productType")
            .then(result =>{
              result = result.data; //{success,result:{}}
              if (result.success){
                this.productTypes = result.result;
              }else{
                this.$message({
                  message: '获取员工数据失败！'+result.message,
                  type: 'error'
                });
              }
            })
            .catch(result=>{
              this.$message({
                message: '系统错误！',
                type: 'error'
              });
            })
      },
      search(){
        this.query.currentPage =1;
        this.getProducts();
      },
			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},
			handleCurrentChange(val) {
				this.query.currentPage = val;
				this.getProducts();
			},
			//获取用户列表
			getProducts() {
        console.log(this.query)
				this.listLoading = true;//加载条，在发起请求之前让它显示出来
				//发起请求获得数据
        this.$http.post("/product",this.query)
            .then(result=>{
              result = result.data;
              if (result.success){
                this.pageInfo = result.result;
              }else {
                this.$message({
                  message: '获取失败'+result.message,
                  type: 'error'
                })
              }
              this.listLoading = false;//关闭加载条
            })
            .catch(result=>{
              this.$message({
                message: '系统错误',
                type: 'error'
              })
            })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = row.id
          console.log(para)
					this.$http.delete('/product/'+para).then((res) => {
						//NProgress.done();
            res = res.data;
            if (res.message){
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.getProducts();
              this.listLoading = false;
            }else {
              this.$message({
                message: '系统异常',
                type: 'error'
              });
            }
          }).catch(ref =>{
            this.$message({
              message: '系统异常',
              type: 'error'
            });
          })
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.productFormVisible = true;
				this.product = Object.assign({}, row);
        this.getProductType();
			},
			//显示新增界面
			handleAdd: function () {
				this.productFormVisible = true;
				this.product = {
          id:null,
          key: '',
          value:'',
          type:'',
          intro: ''
				};
        this.getProductType();
			},
			//编辑
			save: function () {
				this.$refs.productForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.productLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.product);
              this.$http.put("/product",para).then((res) => {
                res = res.data;
                if (res.success){
                  this.$message({
                    message: '保存成功',
                    type: 'success'
                  });
                  this.productFormVisible = false; //关闭对话框
                  this.$refs['productForm'].resetFields(); //重置表单
                  this.getProducts(); //重新加载数据
                }else{
                  this.$message({
                    message: '保存失败,'+res.message,
                    type: 'error'
                  });
                }
                this.productLoading = false;//关闭加载条
							});
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
        console.log(ids)
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					// NProgress.start();
					this.$http.patch("/product/batch",ids).then((res) => {
            res = res.data;
            if (res.message){
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.getProducts();
              this.listLoading = false;
            }else {
              this.$message({
                message: '系统异常',
                type: 'error'
              });
            }
          }).catch(ref =>{
            this.$message({
              message: '系统异常',
              type: 'error'
            });
          })
				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getProducts();
		}
	}

</script>

<style scoped>

</style>